package com.jackrain.nea.ext.permission;

import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.core.webaction.WebAction;

import java.io.Serializable;
import java.util.HashMap;

/**
 * @author lzm
 * @date 2017-11-29
 */
public class AdminPermissionCollection extends PermissionCollection implements Serializable {
    private static final long serialVersionUID = 3656363012942290182L;
    private HashMap<Long, MenuPermissionModel> fullMenuCache = new HashMap<>();  //菜单项权限集合
    private HashMap<Long, ActionPermissionModel> fullActionCache = new HashMap<>(); //动作权限集合

    private TableManager tm;
    private MenuCollection tree;

    public AdminPermissionCollection(TableManager tm, MenuCollection tree) {
        this.tm = tm;
        this.tree = tree;
    }

    @Override
    public void addAction(ActionPermissionModel model) {
        //do nth.
    }

    @Override
    public void addMenu(MenuPermissionModel model) {
        //do nth.
    }

    @Override
    public ActionPermissionModel fetchActionById(Long actionId) {
        WebAction action = tm.getWebAction(actionId.intValue());
        if (action == null) {
            return null;
        }
        ActionPermissionModel model = fullActionCache.get(actionId);
        if (model == null) {
            model = createFullActionPermission(tm, tree, -1L, action);
            fullActionCache.put(actionId, model);
        }
        return model;
    }

    @Override
    public MenuPermissionModel fetchMenuByMenuId(Long menuId) {
        MenuNode node = tree.fetchById(MenuNodeType.MENU, menuId);
        if (node == null) {
            return null;
        }
        MenuPermissionModel model = fullMenuCache.get(menuId);
        if (model == null) {
            model = createFullMenuPermission(-1L, node);
            fullMenuCache.put(menuId, model);
        }
        return model;
    }
}
